/*
 * createIndividualPanel.java
 *
 * Created on 12. Juni 2008, 17:50
 */

package twi.view.manipulation;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JTree;

import prefuse.controls.ControlAdapter;
import prefuse.data.Tree;
import prefuse.util.GraphLib;
import prefuse.visual.VisualItem;

import twi.Utils;
import twi.query.template.NameFactory;
import twi.query.template2.view.DatatypePropertyPanel;
import twi.result.graph.PrefuseGraphFactory;
import twi_project.ErrorDialog;
import twi_project.IndividualAdding;
import twi_project.TWI;

import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.vocabulary.RDFS;

/**
 *
 * @author  Soeren
 */
public class CreateIndividualPanel extends javax.swing.JPanel implements ModificationListener{

	
    private OntClass ontClass;
	private DataPropertyPanel datatypePropPanel;
	private ArrayList<ObjectPropertyPanel> objectPropFrameList = new ArrayList<ObjectPropertyPanel>();
	private ModificationListener listener;
	private Individual individual;
	/** Creates new form createIndividualPanel 
	 * @param listener */
    public CreateIndividualPanel(OntClass ontClass, Individual indi, ModificationListener listener) {
        initComponents();
        this.listener = listener;
        this.jTextField1.setText(NameFactory.createIndividualName(ontClass));
        if (indi != null){
        	this.jTextField1.setText(indi.getLocalName());
        	this.jTextField1.setEditable(false);
        }
        
        this.ontClass = ontClass;        
        
        Tree t = PrefuseGraphFactory.createGraph(TWI.getInstance().getOntologieModel());
        
        ControlAdapter adapter = new ControlAdapter(){

        	long last = 0;
        	private String lastN = null;
        	@Override
        	public void itemClicked(VisualItem item, MouseEvent e) {
        		String itemName = item.getString(GraphLib.LABEL);
        		long curr = System.currentTimeMillis();
        		if (curr - last < 200 && lastN != null && lastN.equals(itemName)){
        			Individual indi = TWI.getInstance().getOntologieModel().getIndividual(itemName);
        			if (indi == null)
        				return ;
        			System.out.println(indi);
        			last = 0;
        			for (int i = 0; i < objectPropFrameList.size(); i++)
        				objectPropFrameList.get(i).tryResourceAsIndividual(indi);
        		}
        		last = System.currentTimeMillis();
        		this.lastN = itemName;
        	}
        	
        };
		JComponent comp = TreeView.demo(t, GraphLib.LABEL, adapter, 100, 200 );
		this.jPanel_tree.setLayout(new BorderLayout());
		this.jPanel_tree.removeAll();
		this.jPanel_tree.add(comp ,BorderLayout.CENTER);
		
        createDatatypePropertys(ontClass, indi);
        createObjectPropertyFrames(ontClass, indi);
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridheight = 1;
        gc.gridwidth = 2;
        gc.gridx = 0;
        gc.gridy = 0;
        this.jPanel_propertys.add(this.datatypePropPanel, gc);
        gc.anchor = GridBagConstraints.WEST;
        gc.gridy++;
        for (int i = 0; i < this.objectPropFrameList.size(); i++){
        	ObjectPropertyPanel f = this.objectPropFrameList.get(i);
        	f.setVisible(true);
        	jPanel_propertys.add(f, gc);
        	gc.gridy++;
        }
    }


    

	private void createObjectPropertyFrames(OntClass ontClass2, Individual indi) {
    	List<OntProperty> list = Utils.getPropertyList(ontClass2, true, false);
    	for (int i = 0; i < list.size(); i++){
    		if (list.get(i).isDatatypeProperty())
    			continue;
    		objectPropFrameList.add(new ObjectPropertyPanel(list.get(i), indi, this) );
    	}
	}
	
	private void createDatatypePropertys(Individual indi) {
		createDatatypePropertys(indi.getOntClass(), indi);
	}

	private void createDatatypePropertys(OntClass ontClass2, Individual indi) {
    	List<OntProperty> list = Utils.getPropertyList(ontClass2);
		ArrayList<DatatypeSingleProperty> propPanelList = new ArrayList<DatatypeSingleProperty>();

		for (int i = 0; i < list.size(); i++){
			OntProperty prop = list.get(i);
			if (!prop.isDatatypeProperty()){
				continue;
			}
			DatatypeProperty dp = prop.asDatatypeProperty();
			String name = dp.getLocalName();
			String range = Utils.getLocalName(dp.getRange());
			String value = null;
			if (indi != null){
				RDFNode valueRDF = indi.getPropertyValue(dp);
				if (valueRDF != null){
					if (valueRDF.isLiteral()){
						value = valueRDF.toString();
					}
				}
			}
			propPanelList.add(new DatatypeSingleProperty(name, range, value));
		}
		
		DataPropertyPanel dpf = new DataPropertyPanel(propPanelList);
		dpf.setVisible(true);
		this.datatypePropPanel = dpf;
	}

	/** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jPanel_tree = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel_propertys = new javax.swing.JPanel();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(twi_project.TWI_ProjectApp.class).getContext().getResourceMap(CreateIndividualPanel.class);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setToolTipText(resourceMap.getString("jTextField1.toolTipText")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setToolTipText(resourceMap.getString("jTextArea1.toolTipText")); // NOI18N
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setToolTipText(resourceMap.getString("jButton1.toolTipText")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addGap(8, 8, 8))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(162, 162, 162)
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel_tree.setName("jPanel_tree"); // NOI18N

        javax.swing.GroupLayout jPanel_treeLayout = new javax.swing.GroupLayout(jPanel_tree);
        jPanel_tree.setLayout(jPanel_treeLayout);
        jPanel_treeLayout.setHorizontalGroup(
            jPanel_treeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 333, Short.MAX_VALUE)
        );
        jPanel_treeLayout.setVerticalGroup(
            jPanel_treeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 178, Short.MAX_VALUE)
        );

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jPanel_propertys.setName("jPanel_propertys"); // NOI18N
        jPanel_propertys.setLayout(new java.awt.GridBagLayout());
        jScrollPane2.setViewportView(jPanel_propertys);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel_tree, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jPanel_tree, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
	String name = this.jTextField1.getText();
	if (name == null || name.isEmpty()){
		new ErrorDialog(null, true, "Add at least a name").setVisible(true);
		return ;
	}
	
	IndividualAdding.createIndividual(this.ontClass.getLocalName(), this.jTextField1.getText());
	IndividualAdding.addProperty(RDFS.comment.getLocalName(), this.jTextArea1.getText(), this.jTextField1.getText());
	this.datatypePropPanel.commit(this.jTextField1.getText());
	for (int i = 0; i < this.objectPropFrameList.size(); i++){
		this.objectPropFrameList.get(i).commit(this.jTextField1.getText());
	}
	if (this.listener != null)
		this.listener.updateModification();
	TWI.getInstance().writeOntology();
	
}//GEN-LAST:event_jButton1ActionPerformed

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
	
}//GEN-LAST:event_jTextField1KeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel_propertys;
    private javax.swing.JPanel jPanel_tree;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
	@Override
	public void updateModification() {
		this.datatypePropPanel.updateModfications();
		for (int i = 0;i < this.objectPropFrameList.size(); i++)
			this.objectPropFrameList.get(i).updateModifications();
		
	}

}
